<template>
  <el-dialog
    title="详细数据"
    :visible.sync="visible"
    width="1000px"
    top="2vh"
    class="dialog-box"
    @open="handleOPen"
    @close="handleClose"
  >
    <div>
      <div class="flex main-title">
        <div class="title flex" style="align-items: flex-end">
          <span style="line-height: 20px; color: #000000">{{ diaTitle }}</span>
          <!-- 如果是点击率或者是转换率 则保留两位小数  并带%符号 -->
          <countTo
            v-show="typeStr === 'ttr' || typeStr === 'conversionRate'"
            :start-val="0"
            separator=","
            :end-val="nowInfo[typeStr] ? nowInfo[typeStr] * 100 : 0"
            :decimals="2"
            :duration="1000"
            class="main-num"
            suffix="%"
          />

          <!-- 如果是点击，下载，安装，展示则为整数 且不带符号  -->
          <countTo
            v-show="
              typeStr === 'impressions' ||
              typeStr === 'taps' ||
              typeStr === 'installs' ||
              typeStr === 'newDownloads' ||
              typeStr === 'redownloads' ||
              typeStr === 'latOninstalls' ||
              typeStr === 'latOffinstalls'
            "
            :start-val="0"
            separator=","
            :end-val="nowInfo[typeStr] ? nowInfo[typeStr] : 0"
            :decimals="0"
            :duration="1000"
            class="main-num roboto-Bold"
          />

          <!-- 如果是其他的  则显示金额单位  且保留两位小数 -->
          <countTo
            v-show="
              typeStr === 'avgCpaAmount' ||
              typeStr === 'avgCptAmount' ||
              typeStr === 'localSpendAmount'
            "
            :start-val="0"
            separator=","
            :end-val="nowInfo[typeStr] ? nowInfo[typeStr] : 0"
            :decimals="2"
            :duration="1000"
            :prefix="unitTxt"
            class="main-num roboto-Bold"
          />
        </div>
        <choose-time
          v-if="visible"
          ref="chooseTimeBox"
          :time-loc-set="false"
          @timeChange="handleTimeChange"
        />
      </div>
      <div v-loading="targetLoading" elemetn-loading-text="数据加载中,请稍候">
        <charts-table
          :id-name="'infoEchart'"
          height="360px"
          :x-data="echartXData"
          :series-data="echartSeriesData"
          :type-str="typeStr"
        >
          <div slot="left">
            <el-radio-group
              v-model="queryEchart.type"
              size="small"
              @change="getTargetChartData"
            >
              <el-radio-button label="DAILY">每天</el-radio-button>
              <el-radio-button
                label="HOURLY"
                :disabled="
                  $getDiffDay(queryEchart.startTime, queryEchart.endTime) > 31
                "
                >每小时</el-radio-button
              >
            </el-radio-group>
          </div>
        </charts-table>
      </div>

      <el-table
        ref="table"
        v-loading="tableLoading"
        elemetn-loading-text="数据加载中,请稍候"
        style="width: 100%"
        class="series-table"
        :data="tableDataList"
        @sort-change="handleSortChange"
      >
        <!-- <el-table-column label="日期" width="200" sortable prop="date" /> -->
        <el-table-column label="日期" width="200" sortable prop="date" />
        <el-table-column :label="diaTitle" align="right">
          <template slot-scope="scope">
            <div style="text-align: rig">
              <!-- 如果是cpt,cpa -->
              <span v-if="typeStr === 'ttr' || typeStr === 'conversionRate'">
                {{ scope.row[typeStr] * 1 }}%</span
              >
              <span
                v-else-if="
                  typeStr === 'impressions' ||
                  typeStr === 'taps' ||
                  typeStr === 'installs' ||
                  typeStr === 'newDownloads' ||
                  typeStr === 'redownloads' ||
                  typeStr === 'latOninstalls' ||
                  typeStr === 'latOffinstalls'
                "
              >
                {{ scope.row[typeStr] * 1 }}</span
              >

              <span v-else
                >{{ unitTxt }} {{ (scope.row[typeStr] * 1).toFixed(2) }}</span
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex" style="justify-content: flex-end; padding: 8px 0">
        <el-pagination
          :current-page="pageNum"
          :page-size="pageSize"
          layout="total,  prev, pager, next, jumper"
          :total="tableData.length"
          @current-change="
            (index) => {
              pageNum = index;
            }
          "
        />
      </div>
    </div>
  </el-dialog>
</template>
<script>
import countTo from "vue-count-to";
import chooseTime from "../../../components/chooseTime/new-index.vue";
import chartsTable from "../../../components/charts-table.vue";

import { findReportCampaignTotal } from "@/api/overView.js";

export default {
  name: "", // ·������
  components: {
    countTo,
    chooseTime,
    chartsTable,
  },
  props: {
    visible: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    typeStr: {
      type: String,
      default: () => {
        return "ttr";
      },
    },

    unit: {
      type: String,
      default: function () {
        return this.$store.state.user.unit;
      },
    },
  },
  data() {
    return {
      order: "descending",
      nowInfo: {},
      tableLoading: false,
      tableData: [],
      pageSize: 5,
      pageNum: 1,
      echartInfo: [], // 具体信息
      queryEchart: {
        audienceType: "countryOrRegion",
        typeValue: "",
        campaignId: "", // 如果不是单个campaign就不填
        country: "",
        countrySX: this.$store.state.user.timeZone, // 时区
        timeZone: this.$store.getters.timeZoneTime, // 时区比UTC时间少几个小时
        startTime: this.$store.state.overview.timeObj.overViewTime.startTime, // 开始时间
        endTime: this.$store.state.overview.timeObj.overViewTime.endTime, // 结束时间
        name: "", // 查询时的名称  模糊查询
        status: "", // 状态
        userId: this.$store.state.user.userInfo.userId,
        adChannelType: "", // 投放位置
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
        currencyType: this.$store.state.user.unit,
        type: "DAILY", // 每天：'DAILY' 每小时'HOURLY'
        teamId: this.$store.state.team.teamId || "", // 团队
        campaignGroupId:
          this.$route.query.serialId || this.$route.query.serialid || 0,
      },
    };
  },
  computed: {
    timeObj() {
      return this.$store.state.overview.timeObj.overViewTime;
    },
    tableDataList() {
      const startNum = this.pageSize * (this.pageNum - 1);
      const endNum = this.pageNum * this.pageSize;

      const tableData = this.tableData.map((item) => {
        const str = item.date.replace(/-/g, "/");
        const time = new Date(str).getTime();
        return {
          ...item,
          time,
        };
      });
      if (this.order === "descending") {
        tableData.sort((a, b) => {
          return b.time - a.time;
        });
      }

      let arr = [];
      if (!this.tableData.length) {
        arr = [];
      } else if (endNum < this.tableData.length) {
        arr = tableData.slice(startNum, endNum);
      } else {
        arr = tableData.slice(startNum);
      }

      return arr;
    },
    // 总数
    totalNum() {
      if (this.echartInfo.now && this.echartInfo.now[this.typeStr]) {
        return this.echartInfo.now[this.typeStr] * 1;
      } else {
        return 0;
      }
    },
    // 金额单位
    unitTxt() {
      if (this.unit === "USD") {
        return "$";
      } else {
        return "￥";
      }
    },
    // 标题
    diaTitle() {
      let str = "";
      switch (this.typeStr) {
        case "impressions":
          str = "展示";
          break;
        case "taps":
          str = "点击";
          break;
        case "installs":
          str = "安装";
          break;

        case "avgCptAmount":
          str = "平均每次点击费用(CPT)";
          break;
        case "avgCpaAmount":
          str = "平均每次转化费用(CPA)";
          break;
        case "ttr":
          str = "点击率";
          break;
        case "conversionRate":
          str = "转化率";
          break;
        case "newDownloads":
          str = "新增下载次数";
          break;
        case "redownloads":
          str = "重新下载次数";
          break;
        case "latOninstalls":
          str = "开启LAT下载";
          break;

        case "latOffinstalls":
          str = "关闭LAT下载";
          break;
      }

      return str;
    },

    echartXData() {
      const arr = this.echartInfo.map((item) => {
        return item.date;
      });
      return arr;
    },
    echartSeriesData() {
      const obj = {
        name: this.diaTitle,
        data: [],
      };
      obj.data = this.echartInfo.map((item) => {
        return item[this.typeStr] * 1;
      });
      return [obj];
    },
  },
  watch: {
    timeObj: {
      deep: true, // ���ȼ�������Ϊ true
      handler: function (newV, oldV) {
        this.handleTimeChange(newV);
      },
    },
    typeStr: {
      // �����Ķ���
      deep: true, // ���ȼ�������Ϊ true
      handler: function (newV, oldV) {
        this.$nextTick(() => {
          this.pageNum = 1;
          this.$forceUpdate();
        });
      },
    },
  },
  // ������
  created() {},
  // ���غ�
  mounted() {},
  // ���ٺ�
  destroyed() {},

  // ����
  methods: {
    handleSortChange(data) {
      // console.log(data,'你好')
      const order = data.order || "descending";
      this.order = order;
    },

    // 弹窗关闭时的函数
    handleClose() {
      this.$emit("update:visible", false);
    },
    handleOPen() {
      this.handleTimeChange(this.timeObj);
    },

    // 时间选择触发事件
    handleTimeChange(data) {
      this.queryEchart.startTime = data.startTime;
      this.queryEchart.endTime = data.endTime;
      this.pageNum = 1;
      if (
        this.$getDiffDay(this.queryEchart.startTime, this.queryEchart.endTime) >
        31
      ) {
        this.queryEchart.type = "DAILY";
      }
      this.getTargetChartData();
    },

    // 核心指标查询表格数据   只需要获取每天的数据变化
    async getTargetChartData() {
      this.tableLoading = true;
      const obj = {
        ...this.queryEchart,
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
        campaignGroupId:
          this.$route.query.serialId || this.$route.query.serialid || 0,
        type: this.queryEchart.type, // 每天：'DAILY' 每小时'HOURLY'
      };

      const res = await findReportCampaignTotal(obj);
      this.tableLoading = false;
      if (res.data.code * 1 === 20000) {
        this.tableData = JSON.parse(JSON.stringify(res.data.data.result));
        this.echartInfo = JSON.parse(JSON.stringify(res.data.data.result));
        this.nowInfo = JSON.parse(JSON.stringify(res.data.data.now));
      } else {
        this.$message.closeAll();
        this.$message.error(
          res.data.message || "趋势对比图表数据获取失败，请稍后重试"
        );
      }
    },
  },
};
</script>

<style scoped lang="scss">
.main-title {
  align-items: flex-end;
  margin-top: -8px;
  margin-bottom: 24px;

  .title {
    .main-num {
      color: #000;
      font-size: 24px;
      line-height: 24px;
      margin-left: 8px;
      font-family: Roboto-Bold, PingFangSC-Medium, PingFangSC, sans-serif !important;
    }
  }
}
</style>
